<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { DefectDefineModel } from '#/api/quality/models';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteDefectDefineApi,
  getDefectDefinePagedListApi,
} from '#/api/quality/defectDefine';
import { $t } from '#/locales';

import { useColumns, useSearchSchema } from './data';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/**
 * 创建缺陷
 */
function onCreate() {
  formModalApi.setData(null).open();
}

/**
 * 编辑缺陷
 */
function onEdit(row: DefectDefineModel) {
  formModalApi.setData(row).open();
}

/**
 * 删除缺陷
 */
function onDelete(row: DefectDefineModel) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.defectName]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteDefectDefineApi(row.id)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.defectName]),
        key: 'action_process_msg',
      });
      refreshGrid();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<DefectDefineModel>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    schema: useSearchSchema(),
    // 控制表单是否显示折叠按钮
    showCollapseButton: true,
    submitOnEnter: true,
  },
  gridOptions: {
    columns: useColumns(onActionClick),
    border: true,
    stripe: true,
    pagerConfig: {},
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getDefectDefinePagedListApi({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    toolbarConfig: {
      custom: true,
      refresh: true,
      zoom: true,
    },
  } as VxeTableGridOptions,
});

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="refreshGrid()" />
    <Grid>
      <template #toolbar-tools>
        <Button type="primary" @click="onCreate()"> 新增缺陷 </Button>
      </template>
    </Grid>
  </Page>
</template>
